package com.suxin.netty.remoting;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

/**
 * @author Tang
 * @classname NettyServerHandler
 * @description [ server handler ]
 * @date 2022/12/14 00:01
 */
@Slf4j
public class NettyServerHandler extends SimpleChannelInboundHandler<RemotingCommand> {

    private final AbstractNettyRemoting nettyRemoting;

    public NettyServerHandler(AbstractNettyRemoting nettyRemoting) {
        super();
        this.nettyRemoting = nettyRemoting;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RemotingCommand msg) throws Exception {
        this.nettyRemoting.processMessageReceived(ctx, msg);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        String eventType = "";
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent stateEvent = (IdleStateEvent) evt;
            switch (stateEvent.state()) {
                case READER_IDLE:
                    eventType = "读事件空闲";
                    break;
                case WRITER_IDLE:
                    eventType = "写事件空闲";
                    break;
                case ALL_IDLE:
                    eventType = "读写事件空闲";
                    break;
                default:
                    break;
            }
        }
        log.info(ctx.channel().remoteAddress() + ":{}!" + eventType);
    }
}
